package cn.ad.server.persistence.redis.serializer;

import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;


/**
 * 序列化包装对象。
 * 用于打logger
 * @author wangwei
 *
 */
public class FalconJsonRedisSerializer implements RedisSerializer<Object>{

	static final Logger logger = LoggerFactory.getLogger(FalconJsonRedisSerializer.class);
	
	private final Charset charset =Charset.forName("UTF8");
	
	private RedisSerializer<Object> serializer;
	
	public FalconJsonRedisSerializer(){
		this.serializer = new GenericJackson2JsonRedisSerializer();
	}
	
	public FalconJsonRedisSerializer(RedisSerializer<Object> serializer){
		this.serializer = serializer;
	}
	
	@Override
	public byte[] serialize(Object t) throws SerializationException {
		try {
			return serializer.serialize(t);
		} catch (Exception e) {
			throw new SerializationException("serialize into JSON error: +"+t.toString(), e);
		}
	}

	@Override
	public Object deserialize(byte[] bytes) throws SerializationException {
		try {
			return serializer.deserialize(bytes);
		} catch (Exception e) {
			throw new SerializationException("deserialize JSON error: " + new String(bytes, charset), e);
		}
	}

}
